package com.ebid.templates.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


/*
       对20号令处理方法
 */
public class ParameterUtils {

    private static Map map = new HashMap();

    public static String get(String key){

        return (map.get(key)==null)? "" : (String) map.get(key);
    }

    public static void set(String key,String value){
        map.put(key,value);
    }

    //传入    json 字符串  解析 json 中的 key value 放入 map 中
    public static void set(String json){
        ObjectMapper jackson = new ObjectMapper();

        try {
            JsonNode node = jackson.readTree(json);
            jsonLeaf(node);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    // 遍历json
    public static void jsonLeaf(JsonNode node){
        if (node.isValueNode())
        {
            return;
        }

        if (node.isObject())
        {
            Iterator<Map.Entry<String, JsonNode>> it = node.fields();
            while (it.hasNext())
            {
                Map.Entry<String, JsonNode> entry = it.next();
                map.put(entry.getKey(),entry.getValue().toString().substring(1,entry.getValue().toString().length()-1));
                jsonLeaf(entry.getValue());
            }
        }

        if (node.isArray())
        {
            Iterator<JsonNode> it = node.iterator();
            while (it.hasNext())
            {
                jsonLeaf(it.next());
            }
        }
    }

}
